package handles

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var shop []models.Shop
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": shop,
	})
	return

}

func Detail(c *gin.Context) {

	id := c.Query("id")

	var shop models.Shop
	redis_key := "detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": shop,
	})
	return

}
